<template>
  <div class="lpkcart">
    <!--1. 头部区域开始 -->
    <div class="toubu">
      <van-nav-bar
        title="购物车"
        left-text="返回"
        right-text="去登录"
        left-arrow
        @click-left="onClickLeft"
        @click-right="onClickRight"
      >
        <template #right>
          <div v-show="true" class="more">
            <van-icon name="more-o" size="1.4rem" color="black" />
          </div>
        </template>
      </van-nav-bar>
      <!--2. 店铺 -->
      <div class="lpkcart-head">
        <van-nav-bar
          left-text="配送至："
          :right-text="address"
          @click-right="onClickRight2"
        />
      </div>
    </div>
    <!-- 更多导航 -->
    <div v-show="isShow" class="showmore">
      <div class="sj"></div>
      <ul>
        <li @click="goto1">
          <van-icon name="home-o" size="1.3rem"></van-icon> 首页
        </li>
        <li @click="goto2">
          <van-icon name="points" size="1.3rem"></van-icon> 分类
        </li>
        <li @click="goto3">
          <van-icon name="contact" size="1.3rem"></van-icon> 个人
        </li>
      </ul>
    </div>

    <div class="in"></div>
    <!-- 头部区域结束 -->
    <!-- 3.购物车区域开始 -->
    <div class="cart" @click="handler">
      <!-- 卡片模板 10号商品-->
      <div class="cart-item" v-for="(item, index) in cart" :key="index">
        <div class="item-1">
          <button :data-id="item.gid">×</button>
          <input
            type="checkbox"
            v-model="checked"
            :id="item.iid"
            :value="item.iid"
            name="button"
          />
          <label :for="item.iid"></label>
          <div class="item-img">
            <img :src="`${baseURL}/jd_card/goods/${item.gpic}`" alt="" />
          </div>
          <div class="item-text">
            <p>{{ item.gtitle }}</p>
            <span>￥{{ item.gprice }}</span>
          </div>
        </div>
        <div class="item-2">
          <div>
            <span class="btns">
              <button :data-i="index" :data-n="-1">-</button>
              <span class="counting">{{ item.count }}</span>
              <button :data-i="index" data-n="+1">+</button>
            </span>
          </div>
        </div>
      </div>
    </div>
    <!-- 购物车区域结束 -->
    <!-- 结算 -->
    <div class="weibu"></div>
    <div class="footer">
      <div class="f-left">
        <input
          type="checkbox"
          id="all"
          name="button"
          v-model="checkedAll"
          @click="selectAll()"
        />
        <label for="all"></label>
        <span>全选</span>
      </div>
      <div class="f-right">
        <span>合计：</span>
        <span>￥{{ total.toFixed(2) }}</span>
        <button @click="pay">结算</button>
      </div>
    </div>
    <!-- <van-dialog v-model="show" title="标题" show-cancel-button>
      
    </van-dialog> -->
  </div>
</template>

<script>
import { Delete, Post } from "../gp.js";
import { Dialog } from "vant";
export default {
  data() {
    return {
      zhifu:'',
      address: "地址",
      cartaddrs: [],
      isShow: false,
      cart_index_selected: 0,
      actions: [
        { text: "首页", icon: "wap-home-o", herf: "/home" },
        { text: "分类", icon: "cluster-o", herf: "/sort" },
        { text: "个人", icon: "contact", herf: "/user" },
      ],
      cart: [],
      checked: [],
      checkedAll: false,
    };
  },
  computed: {
    total() {
      let total = 0;
      for (let i = 0; i < this.checked.length; i++) {
        // console.log(this.checked[i])
        for (let p = 0; p < this.cart.length; p++) {
          if (this.checked[i] == this.cart[p].iid) {
            // console.log(this.cart[p]);
            total += this.cart[p].price * this.cart[p].count;
            this.zhifu=total;
          }
        }
      }
      return total;
    },
  },
  mounted() {
    if (this.$store.state.id == "" && sessionStorage.getItem("id") == null) {
      this.$router.push("/login");
    } else if (sessionStorage.getItem("id")) {
      this.$store.commit("setId", sessionStorage.getItem("id"));
      this.$store.commit("setUname", sessionStorage.getItem("username"));
      this.$store.commit("setIslogin", sessionStorage.getItem("islogin"));
      this.$store.commit("setWallet", sessionStorage.getItem("wallet"));
      this.getData();
    }
  },
  watch: {
    checked: function () {
      // console.log(this.checked)
      if (this.checked.length === this.cart.length) {
        this.checkedAll = true;
      } else {
        this.checkedAll = false;
      }
    }
  },
  methods: {
    getData(){
        let url = "/user/cart";
    let data = {};
      data.lid = this.$store.state.id;
      Post(url, data).then((res) => {
        // console.log(res);
        this.cart = res.data.data;
        // console.log(this.cart)
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    onClickRight() {
      this.isShow = !this.isShow;
    },
    onClickRight2() {
      this.$router.push("/address");

      this.address = sessionStorage.getItem("addr");
    },
    goto1() {
      this.$router.push("/home");
    },
    goto2() {
      this.$router.push("/sort");
    },
    goto3() {
      this.$router.push("/user");
    },
    // 结算，将提交订单信息，is_checked中包含了选中的订单编号，将对应的订单编号的商品信息添加入订单中，同时判断订单状态是已付款还是未付款
    pay() {
      debugger;
      Dialog.confirm({
        title: "余额支付中···",
        // message: '支付方式：余额',
        message: `当前余额：${sessionStorage.getItem("wallet")}`,
        cancelButtonColor: "#ccc",
        confirmButtonColor: "#ee0a24",
      })
        .then(() => {
          if (this.total > sessionStorage.getItem("wallet")) {
            this.$toast("余额不足，请充值");
          } else if (this.total <= 0) {
              this.$toast("请选中商品");
              return;
          }
            // 计算余额，更新用户余额
            let url = "/user/wallet";
            let data1 = {wallet:0};
            console.log(sessionStorage.getItem("wallet") );
            console.log(this.zhifu)
            let ssw=sessionStorage.getItem("wallet");
            data1.wallet = ssw-this.zhifu;
            Post(url, data1).then((res) => {
              console.log(res);
              if(res.data.code==200){
                  this.$toast("支付成功");
                  console.log("余额已更改")
                  // 支付成功后
                  // 1 修改vuex中的余额
                  this.$store.commit('setWallet',data1.wallet);
                  let url2='/order/add';
                  let url3='/user/putoff';
                  // 2.已付款商品加入订单
                  let data2={};
                  let data3={};
                  data2.user_id=sessionStorage.getItem("id");
                  this.checked.forEach((item)=>{
                    data2.goods_id=item.goods_id;
                    data2.count=item.count;
                    data2.addrs_id='';
                    data2.status=2;//等待发货
                    // var mytime=myDate.toLocaleTimeString(); 
                    data2.order_time='';
                    data2.pay_time="";
                    data2.deliver_time='';
                    data2.received_time='';
                    Post(url2,data2).then((res2)=>{
                      console.log(res2);//添加订单的结果
                    })
                    // 3.删除购物车的对应商品
                      data3.iid=item.iid;
                      Delete(url3,data3).then((res3)=>{
                        console.log(res3);//删除购物车商品的结果
                      })
                    })
              }else{
                this.$toast("支付失败");
              }
              
            });
        }
        )
        .catch(() => {
          this.$toast("取消支付");
        });
    },
    handler(e) {
      if (e.target.nodeName == "BUTTON") {
        if (e.target.innerHTML == "×") {
          Dialog.confirm({
            title: "删除该商品",
            message: "确认删除吗？",
            cancelButtonColor: "#ee0a24",
            confirmButtonColor: "#ccc",
          })
            .then(() => {
              // on confirm
              // this.cart.splice(e.target.dataset.i, 1);
              let url="/user/putoff";
              let data={};
              data.goods_id=e.target.dataset.id;
              data.user_id=sessionStorage.getItem("id");
              Delete(url,data).then((res)=>{
                this.getData();
              })
               //
            })
            .catch(() => {
              // next();
            });
        } else {
          let i = e.target.dataset.i;
          this.cart[i].count += parseInt(e.target.dataset.n);
          if (this.cart[i].count == 0) {
            this.cart[i].count = 1;
            this.$toast("不能再减少啦");
          }
        }
      }
    },
    selectAll() {
      if (this.checkedAll) {
        // 全选:true
        this.checked = [];
      } else {
        // 全选
        this.checked = [];
        this.cart.forEach((item) => {
          this.checked.push(item.iid);
        });
      }
      // console.log(this.checked)
    },
  },
};
</script>

<style scoped lang="scss">
@import "../assets/scss/lpkcart.scss";
</style>